package com.aw.baselib.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import com.aw.baselib.interfaces.IPermissionListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.reactivex.functions.Consumer;

/**
 * Created by hzw
 */

public class AwRxPermissionUtil {

    private static AwRxPermissionUtil instance;

    public static String[] permissionApp = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE
    };

    /**
     * 读写权限  自己可以添加需要判断的权限, android 13以上
     */
    public static String[] permissionAppLatest = {
            Manifest.permission.READ_MEDIA_IMAGES,
            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.READ_MEDIA_VIDEO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.POST_NOTIFICATIONS,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT
    };

    /**
     * 读写权限  自己可以添加需要判断的权限
     */
    public static String[] permissionsStorage = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * 读写权限  自己可以添加需要判断的权限, android 13以上
     */
    public static String[] permissionsStorageLatest = {
            Manifest.permission.READ_MEDIA_IMAGES,
            //            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.READ_MEDIA_VIDEO};

    /**
     * 位置权限
     */
    public static String[] permissionsLocation = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    /**
     * 相机权限
     */
    public static String[] permissionsCamera = {
            Manifest.permission.CAMERA};

    /**
     * 通知权限
     */
    public static String[] permissionsNotification = {
            Manifest.permission.POST_NOTIFICATIONS};

    /**
     * 通知权限
     */
    public static String[] permissionsInstallPackage = {
            Manifest.permission.REQUEST_INSTALL_PACKAGES};

    /**
     * 电话权限
     */
    public static String[] permissionsPhone = {
            Manifest.permission.CALL_PHONE};

    /**
     * 蓝牙权限
     */
    public static String[] permissionsBluetooth = {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

    /**
     * 蓝牙权限, android 12以上
     */
    public static String[] permissionsBluetoothLatest = {
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

    public static String[] getAppAllPermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return permissionAppLatest;
        } else {
            return permissionApp;
        }
    }

    public static String[] getStoragePermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return permissionsStorageLatest;
        } else {
            return permissionsStorage;
        }
    }

    public static String[] getBluetoothPermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return permissionsBluetoothLatest;
        } else {
            return permissionsBluetooth;
        }
    }

    /**
     * 判断权限集合
     * permissions 权限数组
     * return true-表示没有改权限  false-表示权限已开启
     */
    public boolean hasStoragePermission (Context mContexts) {
        for (String permission : getStoragePermissions()) {
            if (!lacksPermission(mContexts,permission)) {
                return false;
            }
        }
        return true;
    }

    public boolean hasLocationPermission(Context context) {
        for (String permission : permissionsLocation) {
            if (!lacksPermission(context,permission)) {
                return false;
            }
        }
        return true;
    }
    public boolean hasNotificationPermission(Context context) {
        for (String permission : permissionsNotification) {
            if (!lacksPermission(context,permission)) {
                return false;
            }
        }
        return true;
    }

    public boolean hasPhonePermission(Context context) {
        for (String permission : permissionsPhone) {
            if (!lacksPermission(context,permission)) {
                return false;
            }
        }
        return true;
    }
    public boolean hasCameraPermission(Context context) {
        for (String permission : permissionsCamera) {
            if (!lacksPermission(context,permission)) {
                return false;
            }
        }
        return true;
    }

    public boolean hasBluetoothPermission(Context mContexts) {
        for (String permission : getBluetoothPermissions()) {
            if (!lacksPermission(mContexts,permission)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否缺少权限
     */
    private static boolean lacksPermission(Context mContexts, String permission) {
        AwLog.d("lacksPermission===> " + permission);
        return ContextCompat.checkSelfPermission(mContexts, permission) == PackageManager.PERMISSION_GRANTED;
    }

    private AwRxPermissionUtil() {

    }

    public static AwRxPermissionUtil getInstance() {
        if(instance == null) {
            instance = new AwRxPermissionUtil();
        }
        return instance;
    }

    public void checkPermissions(Activity activity, String[] permissions, final IPermissionListener listener) {
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(listener == null)
                            return;
                        if(aBoolean) {
                            //当所有权限都允许，才会到这里
                            listener.granted();
                        } else {
                            if(ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[0])) {
                                listener.shouldShowRequestPermissionRationale();
                            } else {
                                listener.needToSetting();
                            }

                        }
                    }
                });
    }

    public void checkEachPermission(Activity activity, String[] permissions, Consumer consumer) {
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.requestEach(permissions).subscribe(consumer);
    }

    /**
     * 参考
     * @param activity
     * @param permissions
     * @param listener
     */
    private void checkEachPermissionTemplate(Activity activity, String[] permissions, final IPermissionListener listener) {
        //        RxPermissions rxPermissions = new RxPermissions(activity);
        //        rxPermissions.requestEach(permissions)
        //                .subscribe(new Consumer<Permission>() {
        //                    @Override
        //                    public void accept(Permission permission) throws Exception {
        //                        if (permission.name.equals(Manifest.permission.CAMERA)) {
        //                            //使用permission.name可以获得指定权限获得后的操作
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "照相机权限授权了", Toast.LENGTH_SHORT).show();
        //                        }
        //                        /**
        //                         * 这里需要注意，当我们使用requestEach后，上面对应的权限，
        //                         * 下面都会执行一遍
        //                         *
        //                         * 例如，你上面8个权限都同意后，然后到达这里，
        //                         * 在走8次的permission.granted的判断语句
        //                         *
        //                         * 因此，使用时再加上permission.name判断一下更为合理
        //                         */
        //                        if (permission.granted) {
        //                            //用户已经同意该权限
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户已经同意该权限", Toast.LENGTH_SHORT).show();
        //
        //                        } else if (permission.shouldShowRequestPermissionRationale) {
        //                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,
        //                            // 那么下次再次启动时，还会提示请求权限的对话框
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户拒绝了该权限，没选中『不再询问』", Toast.LENGTH_SHORT).show();
        //
        //                        } else {
        //                            // 用户拒绝了该权限，并且选中『不再询问』
        //                            Toast.makeText(OneByOneActivity.this,
        //                                    "用户拒绝了该权限，并且选中『不再询问』", Toast.LENGTH_SHORT).show();
        //                        }
        //
        //                    }
        //                });


    }

    public static void toAppSetting(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivity(intent);
    }
}
